home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11721 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  99 lines

  1. Path: newshost.uwo.ca!usenet
  2. From: turnbull@canlon.physics.uwo.ca (David Turnbull)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: "free"ing classes when the "new" is inside a function
  5. Date: Fri, 15 Mar 1996 21:26:26 GMT
  6. Organization: University of Western Ontario
  7. Message-ID: <4icna3$7p3@falcon.ccs.uwo.ca>
  8. References: <4ic7a5$94u@falcon.ccs.uwo.ca> <3149B5B8.5C25@bnr.ca>
  9. NNTP-Posting-Host: ditto.physics.uwo.ca
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Joseph Bell <jobell@bnr.ca> wrote:
  13.  
  14. >David Turnbull wrote:
  15. >> 
  16. >> I have code something like
  17. >> 
  18. >> MyClass* Myfunc(){
  19. >>   Class* value;
  20. >> .
  21. >> .
  22. >>   value = new MyClass(........);        <- 1 of several possible constructors
  23. >> .
  24. >>   return value;
  25. >> }
  26. >> 
  27. >> ------ in main---------
  28. >> .
  29. >> Class* value;
  30. >> value=Myfunc();
  31. >> .
  32. >> 
  33. >> How do I free up the memory allocated to value?
  34. >> delete value won't do it.
  35.  
  36. >What is the difference between MyClass and Class?
  37.  
  38. >Consider:
  39.  
  40. >A* returnPtrtoA()
  41. >{
  42. >  A* returnPtr = new A(...);
  43. >  return returnPtr;
  44. >}
  45.  
  46. >void main (void)
  47. >{
  48. >  A* myAPtr = returnPtrtoA();
  49. >  
  50.  
  51. >  delete myAPtr;  // frees object and calls destructor
  52. >}
  53.  
  54. >That works.
  55.  
  56. Sorry, I got careless in my example.  Class and MyClass were supposed
  57. to be the same. In other words, like your example. However, this does
  58. NOT free up the memory!
  59. Or perhaps my simplification of the problem is hiding something. What
  60. I have is closer to
  61.  
  62.  
  63. MyClass*  Level1()
  64. {
  65.      MyClass* result;
  66.     result=Level2();
  67.     return result;
  68. }
  69.  
  70. MyClass*  Level2()
  71. {
  72.      MyClass* result;
  73.     result=Level3();
  74.     return result;
  75. }
  76.  
  77. MyClass*  Level3()
  78. {
  79.      MyClass* result;
  80.     result=new MyClass(..........);
  81.     return result;
  82. }
  83.  
  84. void main(void)
  85. {
  86.  
  87.    MyClass* value;
  88.    value=Level1();
  89.    delete value;
  90.  
  91. }
  92.  
  93. In this case the delete is not freeing memory.
  94. David Turnbull
  95. Department of Physics
  96. University of Western Ontario
  97. London, Ontario, Canada
  98.  
  99.